package com.qep.qms.controller;

import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.qep.common.annotation.Log;
import com.qep.common.core.controller.BaseController;
import com.qep.common.core.domain.AjaxResult;
import com.qep.common.core.page.TableDataInfo;
import com.qep.common.enums.BusinessType;
import com.qep.common.utils.poi.ExcelUtil;
import com.qep.qms.domain.CertificateTemplate;
import com.qep.qms.service.ICertificateTemplateService;

/**
 * 证书模板管理控制器
 */
@RestController
@RequestMapping("/qep/certificate/template")
public class CertificateTemplateController extends BaseController {
    
    @Autowired
    private ICertificateTemplateService certificateTemplateService;
    
    /**
     * 获取证书模板列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CertificateTemplate certificateTemplate) {
        startPage();
        List<CertificateTemplate> list = certificateTemplateService.selectCertificateTemplateList(certificateTemplate);
        return getDataTable(list);
    }
    
    /**
     * 获取证书模板详细信息
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(certificateTemplateService.selectCertificateTemplateById(id));
    }
    
    /**
     * 新增证书模板
     */
    @Log(title = "证书模板管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CertificateTemplate certificateTemplate) {
        return toAjax(certificateTemplateService.insertCertificateTemplate(certificateTemplate));
    }
    
    /**
     * 修改证书模板
     */
    @Log(title = "证书模板管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CertificateTemplate certificateTemplate) {
        return toAjax(certificateTemplateService.updateCertificateTemplate(certificateTemplate));
    }
    
    /**
     * 删除证书模板
     */
    @Log(title = "证书模板管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(certificateTemplateService.deleteCertificateTemplateByIds(ids));
    }
    
    /**
     * 下载模板文件
     */
    @GetMapping("/download/{id}")
    public void downloadTemplate(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        try {
            CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
            if (template == null) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"msg\":\"模板不存在\",\"code\":404}");
                return;
            }
            
            // 获取文件路径 - 实际环境中应该从文件系统或存储服务中获取
            String filePath = template.getTemplateFileUrl();
            if (filePath == null || filePath.trim().isEmpty()) {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"msg\":\"文件路径不存在\",\"code\":404}");
                return;
            }
            
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + 
                               java.net.URLEncoder.encode(template.getName() + ".docx", "UTF-8"));
            
            // 写入响应流 - 实际环境中应该读取真实文件
            String content = "模拟的文件内容 - " + template.getName() + " - ID: " + template.getId();
            response.getOutputStream().write(content.getBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
            logger.error("下载模板失败", e);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"msg\":\"下载失败: " + e.getMessage() + "\",\"code\":500}");
        }
    }
    
    /**
     * 获取Word编辑URL
     */
    @GetMapping("/wordEditUrl/{id}")
    public AjaxResult getWordEditUrl(@PathVariable("id") Long id) {
        CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
        if (template == null) {
            return error("模板不存在");
        }
        
        // 此处为演示，实际应该集成Office Online Server或其他可在线编辑Word的服务
        // 添加认证参数，确保能够正确访问文件
        String token = getRequest().getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        String baseUrl = "https://view.officeapps.live.com/op/embed.aspx?src=";
        String fileUrl = getUrl() + template.getTemplateFileUrl();
        if (token != null && !token.isEmpty()) {
            fileUrl += "?access_token=" + token;
        }
        String editUrl = baseUrl + java.net.URLEncoder.encode(fileUrl, java.nio.charset.StandardCharsets.UTF_8);
        
        return success(editUrl);
    }
    
    /**
     * 提取模板变量
     */
    @GetMapping("/extractVariables/{id}")
    public AjaxResult extractTemplateVariables(@PathVariable("id") Long id) {
        try {
            CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
            if (template == null) {
                return error("模板不存在");
            }
            
            // 此处为演示，实际应该通过解析Word文档提取变量
            // 变量格式为[变量名]
            List<String> variables = new ArrayList<>();
            if ("ULTRASONIC".equals(template.getType())) {
                variables.add("productName");
                variables.add("inspectionDate");
                variables.add("productCode");
                variables.add("inspector");
                variables.add("batchNo");
                variables.add("result");
            } else if ("MAGNETIC".equals(template.getType())) {
                variables.add("productName");
                variables.add("reportNo");
                variables.add("material");
                variables.add("inspectionDate");
                variables.add("standard");
                variables.add("result");
            } else {
                variables.add("productName");
                variables.add("certificateNo");
                variables.add("productionDate");
                variables.add("inspectionDate");
                variables.add("inspector");
                variables.add("result");
            }
            
            return success(variables);
        } catch (Exception e) {
            logger.error("提取模板变量失败", e);
            return error("提取模板变量失败: " + e.getMessage());
        }
    }
    
    /**
     * 保存Word模板变量映射
     */
    @PostMapping("/saveWordTemplate")
    public AjaxResult saveWordTemplate(@RequestBody Map<String, Object> params) {
        try {
            Long id = Long.valueOf(params.get("id").toString());
            List<Map<String, Object>> variables = (List<Map<String, Object>>) params.get("variables");
            
            CertificateTemplate template = certificateTemplateService.selectCertificateTemplateById(id);
            if (template == null) {
                return error("模板不存在");
            }
            
            // 此处仅演示，实际应该保存变量映射到数据库
            // 并更新模板配置
            
            return success();
        } catch (Exception e) {
            logger.error("保存模板变量映射失败", e);
            return error("保存失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取服务URL
     */
    private String getUrl() {
        return "http://localhost:8080";
    }
} 